// 引入SDK核心类，js文件根据自己业务，位置可自行放置
const qqmapsdk = require('../libs/qqmap-wx-jssdk1.2/qqmap.js');
const log = require('../log/log.js')
const app = getApp();

Page({
  data: {
    locate: "",
    city: "",
    district: "",
    latitude: 0,
    longitude: 0,
    hourList: ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"],
    genderList: ["男", "女"],
    pickerHeight: 40
  },
  onShareAppMessage: function () {
    return {
      title: '分享六壬行给你的伙伴吧',
      path: '/pages/index/index',
      imageUrl: '/images/6RXSHARE.png'
    }
  },
  autoStyle: function () {
    var systeminfo = wx.getSystemInfoSync();
    log.info('index-autoStyle-systeminfo-系统参数', systeminfo)
    log.addFilterMsg('indexSystemInfo')

    //px为单位
    var sW = systeminfo.screenWidth;
    var sH = systeminfo.screenHeight

    var rate = 750 / sW;
    log.info('index-autoStyle-rate-屏幕比例', rate);
    log.addFilterMsg('indexRate')

    //rpx为单位
    var rW = parseInt(sW * rate)
    var rH = parseInt(sH * rate)

    //屏幕长宽比
    var hwNum = sH / sW

    //pad的参数
    var pam = 1
    if (hwNum < 1.4) {
      pam = 0.72
    }

    //第一行地图和我的图标占7.5%
    var mapH0 = parseInt(rH * 0.05)

    //图标高度固定
    var mapH1 = parseInt(sH * 0.0499)

    //地图的高度已经自适应
    var mapW2 = rW * 0.75

    //刷新图标的高度
    var refH = parseInt(sH * 0.025)

    this.setData({
      mapH0: mapH0,
      mapH1: mapH1,
      mapW2: mapW2,
      refH: refH
    })
  },
  onLoad: function () {
    log.info('index-onLoad-这里调用了onLoad ： ￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥')

    //是否开启权限
    this.isOpenAuth = false
    log.info('index-onLoad-isOpenAuth', this.isOpenAuth)
    log.addFilterMsg('indexIsOpenAuth')

    //首先清空全局变量
    app.globalData.nowDate = new Date()
    app.globalData.longitude = 0

    //自动样式
    this.autoStyle()

    //开始定位
    var systeminfo = wx.getSystemInfoSync();
    this.locAuth = systeminfo.locationAuthorized
    this.locEnb = systeminfo.locationEnabled

    if (this.locAuth && this.locEnb) {
      this.getLocate()
    } else if (!this.locAuth) {
      wx.showToast({
        title: '您的微信应用未打开定位权限',
        icon: 'none',
        duration: 2500
      })
    } else if (!this.locEnb) {
      wx.showToast({
        title: '您的定位开关尚未打开',
        icon: 'none',
        duration: 2500
      })
    }

    //初始给年List赋值
    var yearList = []
    for (var i = 1900; i <= 2099; i++) {
      yearList.push(i)
    }
    this.setData({
      yearList: yearList,
    })

    //默认年份1991
    this.setData({
      yearValue: [91]
    })
  },
  onShow: function () {
    log.info('index-onShow-这里调用了onShow ： ￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥')
    log.info('index-onShow-longitude', this.data.longitude)

    var self = this

    var systeminfo = wx.getSystemInfoSync();
    self.locAuth = systeminfo.locationAuthorized
    self.locEnb = systeminfo.locationEnabled
    log.info('index-onShow-systeminfo-locAuth微信授权', self.locAuth)
    log.info('index-onShow-systeminfo-locEnb手机定位', self.locEnb)
    log.addFilterMsg('indexLocate')

    if (self.locAuth && self.locEnb) {
      self.getAuthOnShow()
    }

    //打印this
    log.info('index-onShow-this.data-所有值', this.data)
    log.addFilterMsg('indexOnShowAllData')
  },
  onHide: function () {
    log.info('index-onHide-这里调用了onHide ： ￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥')
  },
  onUnload: function () {
    log.info('index-onUnload-这里调用了onUnload ： ￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥')

    //全局变量照样清空掉，不清空后患无穷
    app.globalData.nowDate = new Date()
    app.globalData.longitude = 0

  },
  onReady: function () {
    log.info('index-onReady-这里调用了onReady ： ￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥￥')

    var self = this
    self.myTime = self.selectComponent('#time');

    log.info('index-onReady-当前城市', self.data.city)
    log.info('index-onReady-当前区域', self.data.district)
    log.info('index-onReady-当前定位', self.data.locate)
    log.info('index-onReady-当前经度', self.data.longitude)
    log.addFilterMsg('indexOnReadyLocateMsg')

    log.info('index-onReady-this.data', this.data)
    log.addFilterMsg('indexOnReadyThisData')
  },
  timeUpdate: function () {
    //更新最新时间
    app.globalData.nowDate = new Date()

    var myTime = this.selectComponent('#time');
    myTime.resetTime();
  },
  getAuthOnShow() {
    var self = this
    log.info('index-getAuthOnShow-self.data.locate-当前定位如下所示', self.data.locate)

    if (!self.data.locate) {
      log.info('index-getAuthOnShow-self.data.locate-用户当前无定位显示内容', self.data.locate)
      wx.getSetting({
        success: function (res) {
          log.info('index-getAuthOnShow-getSetting', res)
          if (res.authSetting["scope.userLocation"] == true) {
            log.info('index-getAuthOnShow-res.authSetting-用户已开启定位授权', res.authSetting)
            self.isOpenAuth = true
            self.getLocate()
          } else {
            self.isOpenAuth = false
          }
        }
      })
    }
  },
  getAuth() {
    var self = this
    wx.getSetting({
      success: function (res) {
        log.info('index-getAuth-getSetting', res)
        if (res.authSetting["scope.userLocation"] == true) {
          log.info('index-getAuth-res.authSetting-用户已开启定位授权', res.authSetting)
          self.isOpenAuth = true
          self.getLocate();
        } else {
          wx.showModal({
            title: '位置信息授权',
            content: '位置授权暂未开启，默认使用武汉的经纬度',
            confirmText: '开启授权',
            confirmColor: '#345391',
            cancelText: '仍然拒绝',
            cancelColor: '#999999',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: function (res) {
                    log.info('index-getAuth-openSetting-res.authSetting-打开设置成功', res.authSetting)
                    if (res.authSetting) {
                      if (res.authSetting['scope.userLocation']) {
                        log.info('index-getAuth-openSetting-isOpenAuth == true-已开启权限', res.authSetting)
                        self.isOpenAuth = true
                        self.getLocate()
                      }
                    } else {
                      log.info('index-getAuth-openSetting-isOpenAuth == false-没有开启权限', res.authSetting)
                      self.isOpenAuth = false
                    }
                    log.info('index-getAuth-用户最后是否开启定位授权', res.authSetting)
                    log.addFilterMsg('indexGetAuth')
                  },
                  fail: function () {
                    log.error('index-getAuth-openSetting-用户开启定位授权失败', res)
                  }
                })
              }
              if (res.cancel) {
                self.isOpenAuth = false
                log.info('index-getAuth-cancel-用户自己取消定位', '取消定位，无法使用定位权限，定位失败')
                log.addFilterMsg('indexGetAuthCancel')

                wx.showModal({
                  title: '定位失败',
                  content: '无法使用定位权限，定位失败',
                  confirmText: '确认',
                  confirmColor: '#345391',
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })
  },
  getLocate() {
    let self = this;

    wx.showLoading({
      title: '加载中',
    })
    //定位
    wx.getLocation({
      type: 'wgs84',
      // isHighAccuracy : true,
      // highAccuracyExpireTime : 3500,
      success(res) {
        log.info('index-getLocate-获取定位success', res)

        self.isOpenAuth = true
        var latitude = res.latitude
        var longitude = res.longitude
        //全局变量赋值
        app.globalData.longitude = longitude

        var speed = res.speed
        var accuracy = res.accuracy
        //逆地址解析
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: latitude,
            longitude: longitude
          },
          success: function (res) {
            //微信已经获取权限了
            log.info('index-getLocate-逆地址解析success', res)
            var add = res.result.address_component
            self.setData({
              locate: add.city + add.district,
              city: add.city,
              district: add.district,
              latitude: latitude,
              longitude: longitude
            })
            wx.hideLoading();
          },
        });
      },
      fail(err) {
        log.error('index-getLocate-逆地址解析fail', err)
        wx.hideLoading();
        if (!self.isOpenAuth) {
          self.getAuth()
        }
      }
    })
  },
  locate() {
    if (!this.locAuth) {
      wx.showToast({
        title: '您的微信应用未打开定位权限',
        icon: 'none',
        duration: 2500
      })
      return;
    } else if (!this.locEnb) {
      wx.showToast({
        title: '您的定位开关尚未打开',
        icon: 'none',
        duration: 2500
      })
      return;
    }
    if (this.isOpenAuth) {
      wx.navigateTo({
        url: '../map/map'
      })
    } else {
      this.getAuth()
    }
  },
  onDateTimePicker(e) {
    log.info('index-onDateTimePicker-从日历组件传过来的值', e.detail)
    log.addFilterMsg('indexDateTimePicker')

    //全局变量赋值
    var nowDate = new Date(e.detail.replace(/-/g, '/'))
    app.globalData.nowDate = nowDate
  },
  cleanPickerDate: function () {
    //全局变量赋值
    app.globalData.nowDate = new Date()

    var myTime = this.selectComponent('#time');
    myTime.resetTime();

    //重置年份
    //默认年份1991
    this.setData({
      yearValue: [91],
      genderValue: [0],
      checkValue: false,
      hourValue: [0]
    })

    //全局变量赋值
    app.globalData.birthday = 1991
    app.globalData.gender = 0
    app.globalData.switch = false
    app.globalData.hour = 0
  },
  switchChange(e) {
    var switchVal = e.detail.value

    //全局变量赋值
    app.globalData.switch = switchVal
  },
  bindChangeAge(e) {
    var yearVal = e.detail.value
    console.log(yearVal)

    //全局变量赋值
    app.globalData.birthday = yearVal[0] + 1900

  },
  bindChangeGender(e) {
    var genderVal = e.detail.value
    console.log(genderVal)

    //全局变量赋值
    app.globalData.gender = genderVal[0]
  },
  bindChangeHour(e) {
    var hourVal = e.detail.value
    console.log(hourVal)

    //全局变量赋值
    app.globalData.hour = hourVal[0]
  },
  suiJi: function () {

    console.log(app.globalData)

    if(app.globalData.switch == true){
      var lng = Math.floor(this.data.longitude * 100)
      log.info('index-suiJi-经度数字是多少来着', lng)
      var lat = Math.floor(this.data.latitude * 100)
      log.info('index-suiJi-纬度数字是多少来着', lat)
      var nowTime = new Date()
      var mills = nowTime.getMilliseconds()
      log.info('index-suiJi-毫秒数字是多少来着', mills)
      var param = lng + lat + mills
      log.info('index-suiJi-参数数字是多少来着', param)
      var ranNum = Math.floor(Math.random() * (param + 142857) + 1)
      log.info('index-suiJi-随机数是多少来着', ranNum)
      var realNum = (mills + ranNum + lng + lat) % 12
      log.info('index-suiJi-真实数字是多少来着', realNum)
  
      this.setData({
        hourValue: [realNum]
      })
  
      //全局变量赋值
      app.globalData.hour = realNum
    }
  },
})